package com.qysoft.modules.xxwh.service;

import com.qysoft.modules.common.contants.Contants;
import com.qysoft.rapid.dao.mybatis.RapidDao;
import com.qysoft.rapid.domain.Bean;
import com.qysoft.rapid.exceptions.BizException;

import java.math.BigDecimal;
import java.util.List;

public class JSGLService {
	
	/**
	 * 新增角色
	 * @param jsxx
	 * @throws Exception
	 */
	public static void saveJSXX(Bean jsxx) throws Exception{
		BigDecimal count = (BigDecimal) RapidDao.queryOne("select count(1) from sys_role t where t.name = ?", jsxx.getStr("name"));
		if (count.longValue()>0) { 
			throw new BizException("保存失败，重复的角色名称！");
		}
		//初始化jgid
		jsxx.set("ID", "seq_privid.nextval");
		jsxx.set("EXTEND_FLAG", Contants.YES);
		jsxx.set("FLAG", Contants.YES);
		RapidDao.save("sys_role", "jsid", jsxx);
	}	
	
	
	/**
	 * 删除角色
	 * @param jsid 角色id
	 * @throws Exception
	 */
	public static void delete(String jsid) throws Exception{
		BigDecimal count = (BigDecimal) RapidDao.queryOne("select count(1) from sys_user_role t where t.roleid = ?", jsid);
		if (count.longValue()>0) {
			throw new BizException("删除失败，该角色已被授权！");
		}
		RapidDao.deleteById("sys_user_role", "roleid",jsid);
		RapidDao.deleteById("sys_role", "id",jsid);
	}	

	
	/**
	 * 查询角色信息
	 * @param jsid 角色id
	 * @return
	 * @throws Exception
	 */
	public static Bean queryJSXX(String jsid) throws Exception{
		Bean jsxx = RapidDao.findById("sys_role", "id", jsid);
		return jsxx;
	}
	
	/**
	 * 修改角色信息
	 * @param jsxx
	 * @throws Exception
	 */
	public static void updateJSXX(Bean jsxx) throws Exception{
		RapidDao.update("sys_role", "id", jsxx);
	}
	
	/**
	 * 保存角色授权资源
	 * @param jsid
	 * @param zyids
	 * @throws Exception
	 */
	public static void saveJsZy(String jsid,String zyids) throws Exception{
		//删除所有已授权的资源
		RapidDao.deleteById("sys_role_priv", "roleid", jsid);
		//重新保存授权
		if ("".equals(zyids)) {
			return;
		}
		String[] arrZYID = zyids.split(",");
		for(int i=0;i<arrZYID.length;i++){
			RapidDao.executeSql("insert into sys_role_priv (roleid,privid) values (?,?)", jsid,arrZYID[i]);
		}
	}
	
	/**
	 * 获取角色信息树
	 * @param id
	 * @return
	 * @throws Exception
	 */
	public static List<Bean> queryJsForTree(String id) throws Exception{
		List<Bean> jsList = RapidDao.selectListByXml("query_xtwh_jsxx_tree",id);
		return jsList;
	}
	
}
